package logic;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class SerialWriter {
    private OutputStream out;
    private InputStream in;
    private SerialPort serialPort;

    private String command = "0";

    private String responseArduino;


    public void connect(String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

            if (commPort instanceof SerialPort) {
                serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                in = serialPort.getInputStream();
                out = serialPort.getOutputStream();

                //(new Thread(new SerialReader(in))).start();

                new Thread() {
                    @Override
                    public void run(){
                        readerArduino();
                    }
                }.start();




                //(new Thread(new SerialWriter())).start();
                //run();


            } else {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    public void run(String commandServer) {
        try {
            this.out.write(commandServer.getBytes());
        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public void readerArduino() {

        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            while ((len = this.in.read(buffer)) > -1) {
                System.out.print(new String(buffer, 0, len));
                this.responseArduino = new String(buffer, 0, len);
            }
        } catch (IOException e) {
            System.out.println("SerialReader " + e);
        }
    }

    public String getCommand() {
        return command;
    }

    public void setCommand(String command) {
        this.command = command;
    }

    public InputStream getIn() {
        return in;
    }

    public void setIn(InputStream in) {
        this.in = in;
    }

    public String getResponseArduino() {
        return responseArduino;
    }

    public void setResponseArduino(String responseArduino) {
        this.responseArduino = responseArduino;
    }
}





